using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using AvaAI批量点评系统.Models;
using AvaAI批量点评系统.Services;

namespace AvaAI批量点评系统.ViewModels;

/// <summary>
/// 评语预览和修改界面的ViewModel
/// </summary>
public partial class CommentPreviewViewModel : ViewModelBase
{
    private readonly AliCloudAIService _aiService;

    [ObservableProperty]
    private ObservableCollection<StudentCommentPreview> _studentComments = new();

    [ObservableProperty]
    private StudentCommentPreview? _selectedStudent;

    [ObservableProperty]
    private bool _isProcessing = false;

    [ObservableProperty]
    private string _statusMessage = string.Empty;

    [ObservableProperty]
    private int _totalStudents = 0;

    [ObservableProperty]
    private int _modifiedCount = 0;

    [ObservableProperty]
    private string _courseName = string.Empty;

    [ObservableProperty]
    private string _gradeInfo = string.Empty;

    [ObservableProperty]
    private string _difficultyLevel = string.Empty;

    [ObservableProperty]
    private ObservableCollection<AbilityItem> _abilityItems = new();

    public CommentPreviewViewModel()
    {
        _aiService = new AliCloudAIService();

        // 监听集合变化以更新统计信息
        StudentComments.CollectionChanged += (s, e) => UpdateStatistics();
    }

    /// <summary>
    /// 当选中的学生发生变化时，更新能力评语列表
    /// </summary>
    partial void OnSelectedStudentChanged(StudentCommentPreview? value)
    {
        UpdateAbilityItems();
    }

    /// <summary>
    /// 更新能力评语列表
    /// </summary>
    private void UpdateAbilityItems()
    {
        AbilityItems.Clear();

        if (SelectedStudent?.AbilityEvaluation?.EvaluationItems != null)
        {
            foreach (var item in SelectedStudent.AbilityEvaluation.EvaluationItems)
            {
                var comment = SelectedStudent.AbilityEvaluation.GetSelectedComment(item);

                AbilityItems.Add(new AbilityItem
                {
                    AbilityName = $"{item.Category} - {item.SubCategory}",
                    Comment = comment,
                    Grade = item.SelectedLevel
                });
            }
        }
    }

    /// <summary>
    /// 加载学生评语数据
    /// </summary>
    public void LoadStudentComments(List<StudentComment> comments, string courseName, string grade, string difficulty)
    {
        CourseName = courseName;
        GradeInfo = grade;
        DifficultyLevel = difficulty;

        StudentComments.Clear();
        foreach (var comment in comments)
        {
            var preview = StudentCommentPreview.FromStudentComment(comment);
            
            // 监听每个学生的修改状态变化
            preview.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(StudentCommentPreview.IsModified))
                {
                    UpdateStatistics();
                }
            };
            
            StudentComments.Add(preview);
        }

        UpdateStatistics();
        StatusMessage = $"已加载 {comments.Count} 名学生的评语数据";
    }

    /// <summary>
    /// 更新统计信息
    /// </summary>
    private void UpdateStatistics()
    {
        TotalStudents = StudentComments.Count;
        ModifiedCount = StudentComments.Count(s => s.IsModified);
    }

    /// <summary>
    /// 为选中学生重新生成评语
    /// </summary>
    [RelayCommand]
    private async Task RegenerateSelectedComment()
    {
        if (SelectedStudent == null) return;

        await RegenerateCommentForStudent(SelectedStudent);
    }

    /// <summary>
    /// 为指定学生重新生成评语
    /// </summary>
    [RelayCommand]
    private async Task RegenerateCommentForStudent(StudentCommentPreview student)
    {
        if (student == null || IsProcessing) return;

        try
        {
            student.IsRegenerating = true;
            IsProcessing = true;
            StatusMessage = $"正在为 {student.StudentName} 重新生成评语...";

            // 调用AI服务重新生成评语
            var newComment = await _aiService.GenerateCommentAsync(
                student.StudentName,
                student.Subject,
                student.Grade,
                student.Difficulty,
                false // 使用qwen-turbo非流式处理，速度更快
            );

            // 更新评语内容
            student.Comment = newComment;
            student.IsModified = true; // 标记为已修改
            
            StatusMessage = $"✅ {student.StudentName} 的评语已重新生成";
        }
        catch (Exception ex)
        {
            StatusMessage = $"❌ 重新生成失败: {ex.Message}";
        }
        finally
        {
            student.IsRegenerating = false;
            IsProcessing = false;
        }
    }

    /// <summary>
    /// 批量重新生成所有评语
    /// </summary>
    [RelayCommand]
    private async Task RegenerateAllComments()
    {
        if (IsProcessing) return;

        try
        {
            IsProcessing = true;
            StatusMessage = "正在批量重新生成所有评语...";

            var tasks = StudentComments.Select(async student =>
            {
                student.IsRegenerating = true;
                try
                {
                    var newComment = await _aiService.GenerateCommentAsync(
                        student.StudentName,
                        student.Subject,
                        student.Grade,
                        student.Difficulty,
                        false // 使用qwen-turbo非流式处理，速度更快
                    );
                    
                    student.Comment = newComment;
                    student.IsModified = true;
                }
                finally
                {
                    student.IsRegenerating = false;
                }
            });

            await Task.WhenAll(tasks);
            StatusMessage = $"✅ 已完成 {StudentComments.Count} 名学生的评语重新生成";
        }
        catch (Exception ex)
        {
            StatusMessage = $"❌ 批量重新生成失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    /// <summary>
    /// 重置所有修改
    /// </summary>
    [RelayCommand]
    private void ResetAllModifications()
    {
        foreach (var student in StudentComments)
        {
            student.ResetModifiedStatus();
        }
        StatusMessage = "已重置所有修改状态";
    }

    /// <summary>
    /// 导出修改后的数据（包含能力评语）
    /// </summary>
    [RelayCommand]
    private async Task ExportModifiedData()
    {
        try
        {
            IsProcessing = true;
            StatusMessage = "正在导出修改后的数据（包含能力评语）...";

            var comments = StudentComments.Select(s => s.ToStudentComment()).ToList();

            var excelService = new ExcelService();

            // 获取课程名称和年级信息
            var firstComment = comments.First();
            var courseName = firstComment.Subject ?? "未知课程";
            var grade = firstComment.StartGrade ?? "三年级";

            var generatedFiles = await excelService.CreateStudentCommentsWithAbilityFromTemplateAsync(
                comments, courseName, grade);

            var folderPath = Path.GetDirectoryName(generatedFiles.First());
            var folderName = Path.GetFileName(folderPath);

            StatusMessage = $"✅ 包含能力评语的完整数据已导出到桌面文件夹: {folderName}\n生成了 {generatedFiles.Count} 个文件";
        }
        catch (Exception ex)
        {
            StatusMessage = $"❌ 导出失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task RegenerateAllAbilityEvaluations()
    {
        if (StudentComments?.Count == 0)
        {
            StatusMessage = "没有可重新生成的数据";
            return;
        }

        try
        {
            IsProcessing = true;
            StatusMessage = "正在批量重新生成所有学生的能力评语...";

            int processedCount = 0;
            int totalCount = StudentComments.Count;

            foreach (var studentComment in StudentComments)
            {
                try
                {
                    processedCount++;
                    StatusMessage = $"正在重新生成能力评语... ({processedCount}/{totalCount}) - {studentComment.StudentName}";

                    // 重新生成该学生的能力评语（创建新的实例，会自动初始化默认评语）
                    var newAbilityEvaluation = new StudentAbilityEvaluation();
                    newAbilityEvaluation.StudentName = studentComment.StudentName;

                    // 更新学生的能力评语
                    studentComment.AbilityEvaluation = newAbilityEvaluation;

                    // 短暂延迟避免API调用过于频繁
                    await Task.Delay(500);
                }
                catch (Exception ex)
                {
                    StatusMessage = $"为学生 {studentComment.StudentName} 重新生成能力评语失败: {ex.Message}";
                    await Task.Delay(1000); // 出错时稍长延迟
                }
            }

            StatusMessage = $"✅ 批量重新生成完成！已为 {totalCount} 名学生重新生成能力评语";
        }
        catch (Exception ex)
        {
            StatusMessage = $"❌ 批量重新生成失败：{ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task RegenerateCurrentStudentAbility()
    {
        if (SelectedStudent == null)
        {
            StatusMessage = "请先选择一个学生";
            return;
        }

        try
        {
            IsProcessing = true;
            StatusMessage = $"正在重新生成 {SelectedStudent.StudentName} 的能力评语...";

            // 重新生成该学生的能力评语（创建新的实例，会自动初始化默认评语）
            var newAbilityEvaluation = new StudentAbilityEvaluation();
            newAbilityEvaluation.StudentName = SelectedStudent.StudentName;

            // 更新学生的能力评语
            SelectedStudent.AbilityEvaluation = newAbilityEvaluation;

            // 手动触发属性更改通知
            OnPropertyChanged(nameof(SelectedStudent));

            StatusMessage = $"✅ 已为 {SelectedStudent.StudentName} 重新生成能力评语";
        }
        catch (Exception ex)
        {
            StatusMessage = $"❌ 重新生成能力评语失败：{ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    /// <summary>
    /// 获取修改后的学生评语列表
    /// </summary>
    public List<StudentComment> GetModifiedComments()
    {
        return StudentComments.Select(s => s.ToStudentComment()).ToList();
    }
}
